$(function () {
    $('#link_reg').on('click', function () {
        $('.reg-box').show()
        $('.login-box').hide()
    })

    $('#link_login').on('click', function () {
        $('.login-box').show()
        $('.reg-box').hide()
    })


    var form = layui.form

    form.verify({
        username: [/^[a-zA-Z0-9]{1,10}$/, '用户名必须是1-10位的字母和数字'],
        password: [/^\S{6,12}$/, '密码必须6到12位，且不能出现空格'],
        repwd: function (value) {
            var pass = $('#password').val()

            if (value != pass) {
                return '两次输入密码不一致！'
            }
        }
    })

    $('#form_reg').on('submit', function (event) {
        event.preventDefault()
        var username = $('#username').val()
        var password = $('#password').val()
        var repassword = $('#repassword').val()
        axios({
            method: 'POST',
            url: '/api/reg',
            data: {
                username: username,
                password: password,
                repassword: repassword
            }
        }).then(function (res) {
            if (res.data.code !== 0) {
                return layui.layer.msg(res.data.message)
            }
            layui.layer.msg(res.data.message)
            $('.login-box').show()
            $('.reg-box').hide()
        })
    })

    $('#form_login').on('submit', function (e) {
        e.preventDefault()

        axios({
            method: 'POST',
            url: '/api/login',
            data: $(this).serialize()
        }).then(function (res) {
            if (res.data.code !== 0) {
                return layui.layer.msg(res.data.message)
            }
            layui.layer.msg(res.data.message)
            localStorage.setItem('token', res.data.token)
            location.href = '/index.html'
        })
    })
})